class Paginator:
    def __init__(self, request, queryset, search_keyword=None, search_field='num'):
        self.queryset = queryset
        self.page = int(request.GET.get('page', 1))
        self.page_size = 5
        self.search_keyword = search_keyword
        self.search_field = search_field

        if self.search_keyword:
            self.total_count = self.queryset.filter(**{f"{self.search_field}__icontains": self.search_keyword}).count()
        else:
            self.total_count = self.queryset.count()

        self.total_page_count = self.total_count // self.page_size + (1 if self.total_count % self.page_size else 0)
        self.start = (self.page - 1) * self.page_size
        self.end = self.page * self.page_size

    def get_paginated_queryset(self):
        if self.search_keyword:
            return self.queryset.filter(**{f"{self.search_field}__icontains": self.search_keyword})[self.start:self.end]
        else:
            return self.queryset[self.start:self.end]

    def get_page_control_html(self, plus=5):
        start_page = self.page - plus
        end_page = self.page + plus
        if start_page < 1:
            start_page = 1
            end_page = min(end_page + plus + 1, self.total_page_count)
        if end_page > self.total_page_count:
            end_page = self.total_page_count
            start_page = max(start_page - plus, 1)

        page_str_list = []
        for i in range(start_page, end_page + 1):
            if i == self.page:
                ele = f'<li class="page-item active"><a class="page-link" href="?page={i}&search={self.search_keyword}">{i}</a></li>'
            else:
                ele = f'<li class="page-item"><a class="page-link" href="?page={i}&search={self.search_keyword}">{i}</a></li>'
            page_str_list.append(ele)
        return ''.join(page_str_list)



